const Router = require('koa-router');
const {db, Op,QueryTypes } = require("../../models/db");
const tool = require("../../tools/tool");
const router = new Router();
// 购物车一个商户的
router.post('/app/getCart', async ctx => {
    let user = ctx.user
    let tenantId = user.tenantId
    let id = user.id
    let buId = ctx.request.body.buId
    if(buId) {
        let list = await db.query(`select a.*,b.name invName,b.spec,b.unit1,b.unit2 from cart a inner join v_goods b on a.tenantId=b.tenantId and a.invId=b.id 
         where a.tenantId=${tenantId} 
        and a.uid=${id} and a.buId=${buId} `,{type: QueryTypes.SELECT})
        list.map(row => {
            row.amount = tool.xe.multiply(tool.xe.subtract(row.price, row.deduction), row.qty)
        })
        return ctx.suc('', list)
    }
    else {
        return ctx.suc('', [])
    }

})
// 业务员下所有商户的购物车
router.post('/app/getCartList', async ctx => {
    let user = ctx.user
    let tenantId = user.tenantId
    let id = user.id
    let buId = ctx.request.body.buId
    let sqls = `select a.*,b.name invName,b.spec,b.unit1,b.unit2,c.name buName from cart a inner join v_goods b on a.tenantId=b.tenantId and a.invId=b.id 
         inner join contact c on a.tenantId=c.tenantId and a.buId=c.id 
         where a.tenantId=${tenantId} and a.uid=${id} `
    if(buId) {
        sqls += ` and a.buId=${buId} `
    }
    let list = await db.query(sqls,{type: QueryTypes.SELECT})
    if(list.length > 0) {
        list.map(row => {
            row.price = tool.xe.toNumber(row.price)
            row.deduction = tool.xe.toNumber(row.deduction)
            row.amount = tool.xe.multiply(tool.xe.subtract(row.price, row.deduction), row.qty)
            row.checked = row.checked === 1
        })
        let gp = tool.xe.groupBy(list, 'buId')
        let ret = []
        for(let i in gp) {
            let goods = gp[i].filter(row => {
                return row.checked === true
            })
            let cart = {
                tenantId: gp[i][0].tenantId,
                buId: gp[i][0].buId,
                uid: gp[i][0].uid,
                buName: gp[i][0].buName,
                amount: tool.xe.sum(goods, 'amount'),
                goods: gp[i]
            }
            ret.push(cart)
        }
        return ctx.suc('', ret)
    }
    else {
        return ctx.suc('', [])
    }

})
// 购物车选中
router.post('/app/setCartChecked', async ctx => {
    let user = ctx.user
    let tenantId = user.tenantId
    let cartId = ctx.request.body.id
    let checked = ctx.request.body.checked
    let model = await db.models['cart'].findOne({
        where: {
            tenantId,
            id: cartId
        }
    })
    model.checked = checked?1:0
    await model.save()
    return ctx.suc('')
})

module.exports = router;
